<template>
  <div>
    <el-upload :class="isHidePlus?'hidePlus':''" list-type="picture-card" action="#" :file-list="fileList" :limit="1" :on-preview="handlePreview" :on-remove="handleRemove" :before-upload="handleBeforeUpload" :http-request="upload" :on-change="handleChange">
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="isShow" :text-inside="true" :stroke-width="26" :percentage="percent" />
    <el-dialog
      title="预览"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <img :src="imgUrl" alt="" style="width:100%;display:block;margin:0 auto;">
    </el-dialog>

  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDmKF1OZnGwPeh9MR6bwUofX80vd6OBRM9',
  SecretKey: 'jCevznLEwOaVIYaNYaXGjxxlKfw8G9nX'
})
export default {
  name: '',
  data() {
    return {
      fileList: [],
      imgUrl: '',
      dialogVisible: false,
      percent: 0,
      isShow: false
    }
  },
  computed: {
    // 只要有图片，+号图标就会隐藏
    isHidePlus: function() {
      return this.fileList.length > 0
    }
  },
  methods: {
    handlePreview(file) {
      console.log(file)
      this.imgUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    // return false意思就是阻止文件上传
    handleBeforeUpload(file) {
      // console.log(file)
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('只能上传图片')
        return false
      }
      const maxSize = 5 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('大小不能超过5MB')
        return false
      }
      this.isShow = true
    },
    upload(params) {
      console.log(params)
      // 接下来，就把params.file上传到腾讯云
      cos.putObject({
        Bucket: 'heima-1300357219', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: Date.now() + params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          // console.log(JSON.stringify(progressData)) 0.1
          this.percent = (progressData.loaded / progressData.total) * 100
        }
      }, (err, data) => {
        // console.log(err || data)
        console.log(err)
        // console.log(data)
        if (err) return this.$message.error('上传失败')
        this.fileList = [
          { name: data.Location, url: 'https://' + data.Location }
        ]
      })
    },
    handleChange(file, fileList) {
      this.fileList = fileList
    }
  }
}
</script>

<style scoped lang="scss">
 .hidePlus ::v-deep .el-upload--picture-card{
  display: none;
}
::v-deep .el-progress-bar__outer{
  width:160px;
}
</style>
